package com.tfos.study.mvc.converter.fastjson.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.Charset;
import java.util.List;

/**
 * 类功能说明：实现WebMvcConfigurer接口来配置FastJsonHttpMessageConverter，Spring Boot2.0版本以后推荐使用这种方式来进行web配置，这样不会覆盖掉Spring Boot的一些默认配置. <br/>
 * 公司名称：TF（腾飞）开源 <br/>
 * 作者：luorongxi <br/>
 */
@Configuration
public class CustomWebMvcConfigurer implements WebMvcConfigurer {

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();
        config.setSerializerFeatures(
                //输出值为null的字段;
                SerializerFeature.WriteMapNullValue
                //List字段如果为null,输出为[],而非null;
                ,SerializerFeature.WriteNullListAsEmpty
                //字符类型字段如果为null,输出为"",而非null;
                ,SerializerFeature.WriteNullStringAsEmpty
                //数值字段如果为null,输出为0,而非null;
                ,SerializerFeature.WriteNullNumberAsZero
                //Boolean字段如果为null,输出为false,而非null;
                ,SerializerFeature.WriteNullBooleanAsFalse
                //消除对同一对象循环引用的问题,默认为false;
                ,SerializerFeature.DisableCircularReferenceDetect
                //全局修改日期格式,默认为false。
                //,SerializerFeature.WriteDateUseDateFormat
                );
        converter.setFastJsonConfig(config);
        converter.setDefaultCharset(Charset.forName("UTF-8"));
        converters.add(converter);
    }

}
